//
//  BibleTitleView.m
//  GC_OC
//
//  Created by 曾 on 2022/1/17.
//

#import "BibleTitleView.h"
#import "SelectionVersionView.h"
#import "SelectChineseView.h"
#import "GenesisView.h"
@interface BibleTitleView()<SelectionVersionViewDelegate,SelectChineseViewDelegate,SelectGenesisViewDelegate>

@property (nonatomic, strong)NSDictionary* dic;
@property (nonatomic, strong)SelectionVersionView* selectionVersionView;
@property (nonatomic, strong)SelectChineseView*    selectChineseView;
@property (nonatomic, strong)GenesisView*          selectGenesisView;

@property (nonatomic, strong)UIButton *leftButton;
@property (nonatomic, strong)UIButton *rightButton;
@property (nonatomic, assign)CGFloat leftX;
@property (nonatomic, assign)CGFloat rightX;
@property (nonatomic, strong)UIButton *firstButton;
@property (nonatomic, strong)UIButton *secondButton;
@property (nonatomic, strong)UIButton *thirdButton;

@end

@implementation BibleTitleView

-(instancetype)initWithFrame:(CGRect)frame andDic:(NSDictionary*)dic idString:(NSString *)idString
{
    self=[super initWithFrame:frame];
    if(self)
    {
        self.dic = dic;
        self.idString = idString;

        NSArray* array=@[@"选择",@"",@""];
        self.firstButton = [self createButtonWithTitle:array[0]];
        self.secondButton = [self createButtonWithTitle:array[1]];
        self.thirdButton = [self createButtonWithTitle:array[2]];
        
        [self addSubview:self.selectionVersionView];
        [self addSubview:self.selectChineseView];
        [self addSubview:self.selectGenesisView];
        
        [self addSubview:self.leftButton];
        [self.leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.selectionVersionView.mas_right).offset(-15);
            make.width.equalTo(@(30));
            make.height.equalTo(@(30));
            make.centerY.equalTo(self).offset(160);
        }];
        [self addSubview:self.rightButton];
        [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.selectChineseView.mas_right).offset(-15);
            make.width.equalTo(@(30));
            make.height.equalTo(@(30));
            make.centerY.equalTo(self).offset(160);
        }];
        
        [self updateView];
        
        [self addSubview:self.firstButton];
        [self addSubview:self.secondButton];
        [self addSubview:self.thirdButton];

        [self.firstButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.left.right.equalTo(self.selectionVersionView);
            make.height.equalTo(@(topHeight-StatusBarHeight));
        }];
        [self.secondButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.left.right.equalTo(self.selectChineseView);
            make.height.equalTo(@(topHeight-StatusBarHeight));
        }];
        
        [self.thirdButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.left.right.equalTo(self.selectGenesisView);
            make.height.equalTo(@(topHeight-StatusBarHeight));
        }];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCurrentSong:) name:kUpdateCurrentPlayUI object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateNext) name:@"noNext" object:nil];;
        
    }
    return self;
}

- (void)updateCurrentSong:(NSNotification *)notify {
    NSDictionary *current = notify.object;
    [self.selectGenesisView updateCurrentWith:current];

}

- (void)updateNext {
    if([self.selectChineseView hasNextAndUpdateNext] == true) {
        if ([self.selectGenesisView checkAndPlayFirst] == false) {
            [self updateNext];
        }
    } else {
        if ([self.selectionVersionView hasNextAndUpdateNext] == true) {
            if([self.selectChineseView hasNextAndUpdateNext] == true) {
                if ([self.selectGenesisView checkAndPlayFirst] == false) {
                    [self updateNext];
                }
            }
        }
    }
}

- (void)updateView {
    CGFloat leftWidth = [self readValue:[self firstKey]];

    CGFloat rightWidth = [self readValue:[self secondKey]];

    [self.selectionVersionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.equalTo(self);
        make.top.equalTo(@(topHeight-StatusBarHeight));
        make.width.equalTo(@(leftWidth));
    }];
    
    [self.selectGenesisView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(self);
        make.top.equalTo(@(topHeight-StatusBarHeight));
        make.width.equalTo(@(rightWidth));
    }];
    
    [self.selectChineseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self);
        make.top.equalTo(@(topHeight-StatusBarHeight));
        make.left.equalTo(self.selectionVersionView.mas_right);
        make.right.equalTo(self.selectGenesisView.mas_left);
    }];

    
    self.leftX = leftWidth + 15;
    self.rightX = self.frame.size.width - rightWidth - 15;
}

-(SelectionVersionView*)selectionVersionView
{
    if(!_selectionVersionView)
    {
        NSArray *mediaClass = self.dic[@"media_class"];
        _selectionVersionView=[[SelectionVersionView alloc] initWithArray:mediaClass andDelegate:self];
        NSString *selectVerionStr = mediaClass.count==0 ? @"" : mediaClass[0][@"name"];
        [self.secondButton setTitle:selectVerionStr forState:UIControlStateNormal];
    }
    return _selectionVersionView;
}

-(SelectChineseView*)selectChineseView
{
    if(!_selectChineseView)
    {
        _selectChineseView = [[SelectChineseView alloc] initWithIdStr:self.dic[@"media_class"][0][@"id"] andDelegate:self];
    }
    return _selectChineseView;
}

-(GenesisView*)selectGenesisView
{
    if(!_selectGenesisView)
    {
        _selectGenesisView=[[GenesisView alloc]initWithDelegate:self];
//        NSArray *array = [NSArray array];
//        NSArray *media_class = self.dic[@"media_class"];
//        if (media_class.count > 0) {
//            
//        }
//        _selectGenesisView=[[GenesisView alloc] initWithArray:<#(nonnull NSArray *)#> delegate:<#(nonnull id<SelectGenesisViewDelegate>)#>];
    }
    return _selectGenesisView;
}
/**选择了版本*/
-(void)SelectVersionIDStr:(NSString *)idStr
{
    if([_selectChineseView.idString integerValue] != [idStr integerValue]) {
        [_selectChineseView upDateIDStr:idStr];
    }
}
/**选择了协会*/
-(void)selectChineseViewIDStr:(NSString*_Nullable)idStr
{
    [_selectGenesisView upDateIDStr:idStr];
}
/**获取数据完毕*/
-(void)upDateSelectChineseDown:(NSString*)idStr
{
    [self.selectGenesisView upDateIDStr:idStr];
}
-(void)upDateUI
{
    [_selectionVersionView upDateUI];
}

- (void)upDateChineseUIWithTitle:(NSString *)title {
    [self.thirdButton setTitle:[self handleStringWithString:title].firstObject forState:UIControlStateNormal];
}

- (void)upDateVersionUIWithTitle:(NSString *)title {
    [self.secondButton setTitle:[self handleStringWithString:title].firstObject forState:UIControlStateNormal];
}

- (void)upDateGenesisUIWithTitle:(NSString *)title {
//    [self.selectChineseView saveIdStr];
//    [self.selectGenesisView saveIdStr];
//    [self.selectionVersionView saveIdStr];
}

- (void)leftAction:(UIPanGestureRecognizer *)recognizer {
    [self movingBtn:recognizer];
}

- (void)rightAction:(UIPanGestureRecognizer *)recognizer {
    [self movingBtn:recognizer];
}

-(void)movingBtn:(UIPanGestureRecognizer *)recognizer{
    UIButton *button = (UIButton *)recognizer.view;
    CGPoint translation = [recognizer translationInView:button];
    
    if(recognizer.state == UIGestureRecognizerStateBegan){
        
    }else if(recognizer.state == UIGestureRecognizerStateChanged){
        CGFloat currentX = button.center.x + translation.x;

        if (button == self.leftButton) {
            if (currentX < self.rightX) {
                button.center = CGPointMake(currentX, button.center.y);
                [recognizer setTranslation:CGPointZero inView:button];
                [self.selectionVersionView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.left.equalTo(self);
                    make.top.equalTo(@(topHeight-StatusBarHeight));
                    make.width.equalTo(@(currentX));
                }];
            }
        }
        if (button == self.rightButton) {
            if (currentX > self.leftX) {
                button.center = CGPointMake(currentX, button.center.y);
                [recognizer setTranslation:CGPointZero inView:button];
                [self.selectGenesisView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.right.equalTo(self);
                    make.top.equalTo(@(topHeight-StatusBarHeight));
                    make.width.equalTo(@(self.frame.size.width - currentX));
                }];
            }
        }
    }else if(recognizer.state == UIGestureRecognizerStateEnded){
        CGFloat newX = button.center.x;
        if (button == self.leftButton) {
            self.leftX = newX + 15;
            [self saveValue:newX key:[self firstKey]];
        }
        if (button == self.rightButton) {
            self.rightX = newX - 15;
            CGFloat width = self.frame.size.width - newX;
            [self saveValue:width key:[self secondKey]];
        }
    }
}
- (void)setIdString:(NSString *)idString {
    _idString = [NSString stringWithFormat:@"%@",idString];
}

- (NSString *)firstKey {
    return [NSString stringWithFormat:@"%@firstXKey",self.idString];
}

- (NSString *)secondKey {
    return [NSString stringWithFormat:@"%@rightXKey",self.idString];
}

- (void)saveValue:(CGFloat)value key:(NSString *)key {
    NSArray *personInfo = @[@(value)];

    NSString *cachePatch =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [cachePatch stringByAppendingPathComponent:key];
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
    [personInfo writeToURL:fileUrl atomically:YES];
}

- (CGFloat)readValue:(NSString *)key {
    //获取需要读取数据plist路径
    NSString *cachePatch = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [cachePatch stringByAppendingPathComponent:key];

    //将plist文件中数据转换成数组形式输出（要预先知道plist中数据类型，否则无法读出）
    NSArray *products = [NSArray arrayWithContentsOfFile:filePath];
    if (products == nil) {
        return self.frame.size.width / 3;
    }
    return [products.firstObject floatValue];
}

- (UIButton *)createButtonWithTitle:(NSString *)title {
    UIButton* btn=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:AppMainColor forState:UIControlStateNormal];
    btn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)];
    return btn;
}

- (UIButton *)leftButton {
    if (!_leftButton) {
        _leftButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setImage:[UIImage imageNamed:@"tuozhuai-1"] forState:UIControlStateNormal];
            UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(leftAction:)];
            [button addGestureRecognizer:pan];

            button;
        });
    }
    return _leftButton;
}

- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setImage:[UIImage imageNamed:@"tuozhuai-1"] forState:UIControlStateNormal];
            UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(rightAction:)];
            [button addGestureRecognizer:pan];
            button;
        });
    }
    return _rightButton;
}

//去除字符串中用括号括住的位置
- (NSArray *)handleStringWithString:(NSString *)str{
    NSString *string = [str stringByReplacingOccurrencesOfString:@"(" withString:@"|"];
    string = [string stringByReplacingOccurrencesOfString:@"（" withString:@"|"];
    string = [string stringByReplacingOccurrencesOfString:@")" withString:@"|"];
    string = [string stringByReplacingOccurrencesOfString:@"）" withString:@"|"];
    NSArray *infoArr = [string componentsSeparatedByString:@"|"];
    return infoArr;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
